from Acquisition import aq_inner
from Products.Five import BrowserView
from Products.CMFPlone.utils import getToolByName

from collective.contacts.interfaces import IPerson, \
                                           IGroup, \
                                           IOrganization

ISRCH = (IOrganization,)
ISRCH_INNER = (IGroup, IPerson,)
DEFAULT_FOLDER_LAYOUT = "folder_summary_view"

class AddressBook(BrowserView):
    '''
    lists collective.contacts address book
    as a simple hierarchical list of members
    '''
    @property
    def portal_catalog(self):
        return getToolByName(self.context, 'portal_catalog', None)

    @property
    def context_path(self):
        return '/'.join(self.context.getPhysicalPath())

    @property 
    def reference_catalog(self):
        return getToolByName(self.context, 'reference_catalog', None)
    
    def get_org_members(self, org_uuid):
        member_brains = []
        if self.reference_catalog is not None:
            referenced_objects = \
                            self.reference_catalog(targetUID = org_uuid)
            lookup_uuids = [ritem.sourceUID 
                           for ritem in referenced_objects]
            if self.portal_catalog is not None:
                return self.portal_catalog(UID = lookup_uuids,
                                    object_provides = [ii.__identifier__ 
                                                for ii in ISRCH_INNER])
        return member_brains

    def ct_query(self):
        query = dict(
                object_provides = [ii.__identifier__ for ii in ISRCH],
                path = self.context_path,
        )
        return query

    def contact_list(self):
        if self.portal_catalog is not None:
            obrains = self.portal_catalog(self.ct_query())
            return [{'organization': obrain,
                     'contacts': self.get_org_members(obrain.UID)
                    }
             for obrain in obrains
            ]
        else:
            return []

class RenderOnlyChild(BrowserView):
    """
    Redirects to an only child in a folder or renders folder summary
    """    
    def __call__(self):
        RESPONSE = self.request.response
        folder = aq_inner(self.context)
        children_ids = folder.objectIds()
        if len(children_ids) == 1:
            child_object = getattr(folder, children_ids[0])
            return RESPONSE.redirect(child_object.absolute_url())
        return self.getDefaultTemplate().render()

    def getDefaultTemplate(self):
        template = self.context.unrestrictedTraverse(DEFAULT_FOLDER_LAYOUT)
        return template
